import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface MedicalRecord {
  id: string
  patientId: string
  patientName: string
  doctorId: string
  doctorName: string
  department: string
  visitDate: string
  visitType: '门诊' | '急诊' | '住院' | '体检'
  chiefComplaint: string
  presentIllness: string
  pastHistory: string
  familyHistory: string
  personalHistory: string
  physicalExamination: string
  auxiliaryExamination: string[]
  diagnosis: {
    primary: string[]
    secondary: string[]
    differential: string[]
  }
  treatment: {
    medications: Array<{
      name: string
      dosage: string
      frequency: string
      duration: string
      notes: string
    }>
    procedures: string[]
    advice: string[]
  }
  followUp: {
    required: boolean
    date: string
    instructions: string
  }
  attachments: Array<{
    id: string
    name: string
    type: 'image' | 'document' | 'report'
    url: string
    uploadDate: string
  }>
  status: '草稿' | '已完成' | '已审核' | '已归档'
  createdAt: string
  updatedAt: string
  signatures: Array<{
    role: '主治医师' | '审核医师' | '科主任'
    doctorId: string
    doctorName: string
    signDate: string
    status: '已签名' | '待签名' | '已拒绝'
    reason?: string
  }>
}

export interface MedicalTemplate {
  id: string
  name: string
  category: string
  department: string
  content: {
    chiefComplaint: string
    presentIllness: string
    physicalExamination: string
    diagnosis: string[]
    treatment: string[]
  }
  isActive: boolean
  createdBy: string
  createdAt: string
}

export const useMedicalRecordStore = defineStore('medicalRecord', () => {
  const medicalRecords = ref<MedicalRecord[]>([
    {
      id: 'MR001',
      patientId: 'P001',
      patientName: '张三',
      doctorId: 'D001',
      doctorName: '王医生',
      department: '内分泌科',
      visitDate: '2024-01-20',
      visitType: '门诊',
      chiefComplaint: '口渴、多尿3个月',
      presentIllness: '患者3个月前开始出现口渴、多尿症状，每日饮水量约3000ml，夜尿增多，体重下降约5kg。',
      pastHistory: '否认高血压、心脏病史',
      familyHistory: '父亲有糖尿病史',
      personalHistory: '不吸烟，偶尔饮酒',
      physicalExamination: 'T: 36.5°C, P: 78次/分, R: 18次/分, BP: 130/80mmHg。一般情况良好，皮肤黏膜无异常。',
      auxiliaryExamination: ['空腹血糖: 8.5mmol/L', '糖化血红蛋白: 8.2%', '尿常规: 尿糖+++'],
      diagnosis: {
        primary: ['2型糖尿病'],
        secondary: [],
        differential: ['1型糖尿病', 'MODY']
      },
      treatment: {
        medications: [
          {
            name: '二甲双胍',
            dosage: '0.5g',
            frequency: '每日2次',
            duration: '4周',
            notes: '餐后服用'
          }
        ],
        procedures: [],
        advice: ['控制饮食', '适量运动', '定期监测血糖']
      },
      followUp: {
        required: true,
        date: '2024-02-20',
        instructions: '复查空腹血糖、糖化血红蛋白'
      },
      attachments: [],
      status: '已完成',
      createdAt: '2024-01-20T09:30:00',
      updatedAt: '2024-01-20T10:15:00',
      signatures: [
        {
          role: '主治医师',
          doctorId: 'D001',
          doctorName: '王医生',
          signDate: '2024-01-20T10:15:00',
          status: '已签名'
        }
      ]
    }
  ])

  const medicalTemplates = ref<MedicalTemplate[]>([
    {
      id: 'MT001',
      name: '糖尿病门诊模板',
      category: '内分泌',
      department: '内分泌科',
      content: {
        chiefComplaint: '血糖升高',
        presentIllness: '患者因血糖升高就诊...',
        physicalExamination: 'T: °C, P: 次/分, R: 次/分, BP: mmHg...',
        diagnosis: ['2型糖尿病'],
        treatment: ['控制饮食', '适量运动', '监测血糖']
      },
      isActive: true,
      createdBy: 'D001',
      createdAt: '2024-01-15T10:00:00'
    }
  ])

  const currentRecord = ref<MedicalRecord | null>(null)
  const searchQuery = ref('')
  const filterStatus = ref('')
  const filterDepartment = ref('')
  const filterDateRange = ref<[string, string] | null>(null)
  const loading = ref(false)

  // 获取病历列表
  const getMedicalRecords = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return medicalRecords.value
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取病历
  const getMedicalRecordById = (id: string) => {
    return medicalRecords.value.find(r => r.id === id)
  }

  // 根据患者ID获取病历
  const getMedicalRecordsByPatient = (patientId: string) => {
    return medicalRecords.value.filter(r => r.patientId === patientId)
  }

  // 根据医生ID获取病历
  const getMedicalRecordsByDoctor = (doctorId: string) => {
    return medicalRecords.value.filter(r => r.doctorId === doctorId)
  }

  // 创建病历
  const createMedicalRecord = async (record: Omit<MedicalRecord, 'id' | 'createdAt' | 'updatedAt' | 'signatures'>) => {
    loading.value = true
    try {
      const newRecord: MedicalRecord = {
        ...record,
        id: `MR${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        signatures: []
      }
      medicalRecords.value.unshift(newRecord)
      return newRecord
    } finally {
      loading.value = false
    }
  }

  // 更新病历
  const updateMedicalRecord = async (id: string, updates: Partial<MedicalRecord>) => {
    loading.value = true
    try {
      const index = medicalRecords.value.findIndex(r => r.id === id)
      if (index > -1) {
        medicalRecords.value[index] = {
          ...medicalRecords.value[index],
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return medicalRecords.value[index]
      }
      throw new Error('病历不存在')
    } finally {
      loading.value = false
    }
  }

  // 删除病历
  const deleteMedicalRecord = async (id: string) => {
    loading.value = true
    try {
      const index = medicalRecords.value.findIndex(r => r.id === id)
      if (index > -1) {
        medicalRecords.value.splice(index, 1)
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 搜索病历
  const searchMedicalRecords = (query: string) => {
    searchQuery.value = query
    if (!query) return medicalRecords.value
    
    return medicalRecords.value.filter(record => 
      record.patientName.includes(query) ||
      record.doctorName.includes(query) ||
      record.department.includes(query) ||
      record.chiefComplaint.includes(query) ||
      record.diagnosis.primary.some(d => d.includes(query))
    )
  }

  // 按状态筛选
  const filterRecordsByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return medicalRecords.value
    
    return medicalRecords.value.filter(record => record.status === status)
  }

  // 按科室筛选
  const filterRecordsByDepartment = (department: string) => {
    filterDepartment.value = department
    if (!department) return medicalRecords.value
    
    return medicalRecords.value.filter(record => record.department === department)
  }

  // 按日期范围筛选
  const filterRecordsByDateRange = (dateRange: [string, string] | null) => {
    filterDateRange.value = dateRange
    if (!dateRange) return medicalRecords.value
    
    const [startDate, endDate] = dateRange
    return medicalRecords.value.filter(record => 
      record.visitDate >= startDate && record.visitDate <= endDate
    )
  }

  // 签名病历
  const signMedicalRecord = async (
    recordId: string, 
    doctorId: string, 
    doctorName: string, 
    role: MedicalRecord['signatures'][0]['role']
  ) => {
    loading.value = true
    try {
      const record = medicalRecords.value.find(r => r.id === recordId)
      if (!record) throw new Error('病历不存在')

      const signature = {
        role,
        doctorId,
        doctorName,
        signDate: new Date().toISOString(),
        status: '已签名' as const
      }

      const existingSignatureIndex = record.signatures.findIndex(s => s.role === role)
      if (existingSignatureIndex > -1) {
        record.signatures[existingSignatureIndex] = signature
      } else {
        record.signatures.push(signature)
      }

      record.updatedAt = new Date().toISOString()

      // 检查是否所有必要签名已完成
      const requiredSignatures = ['主治医师']
      const completedSignatures = record.signatures.filter(s => s.status === '已签名').map(s => s.role)
      
      if (requiredSignatures.every(rs => completedSignatures.includes(rs))) {
        record.status = '已审核'
      }

      return record
    } finally {
      loading.value = false
    }
  }

  // 获取待签名病历
  const getPendingSignatureRecords = (doctorId: string, role: MedicalRecord['signatures'][0]['role']) => {
    return medicalRecords.value.filter(record => {
      const signature = record.signatures.find(s => s.role === role)
      return !signature || signature.status === '待签名'
    })
  }

  // 添加附件
  const addAttachment = async (recordId: string, attachment: Omit<MedicalRecord['attachments'][0], 'id' | 'uploadDate'>) => {
    loading.value = true
    try {
      const record = medicalRecords.value.find(r => r.id === recordId)
      if (!record) throw new Error('病历不存在')

      const newAttachment = {
        ...attachment,
        id: `ATT${Date.now()}`,
        uploadDate: new Date().toISOString()
      }

      record.attachments.push(newAttachment)
      record.updatedAt = new Date().toISOString()

      return newAttachment
    } finally {
      loading.value = false
    }
  }

  // 删除附件
  const removeAttachment = async (recordId: string, attachmentId: string) => {
    loading.value = true
    try {
      const record = medicalRecords.value.find(r => r.id === recordId)
      if (!record) throw new Error('病历不存在')

      const index = record.attachments.findIndex(a => a.id === attachmentId)
      if (index > -1) {
        record.attachments.splice(index, 1)
        record.updatedAt = new Date().toISOString()
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 模板管理
  const getTemplates = () => {
    return medicalTemplates.value
  }

  const createTemplate = async (template: Omit<MedicalTemplate, 'id' | 'createdAt'>) => {
    const newTemplate: MedicalTemplate = {
      ...template,
      id: `MT${Date.now()}`,
      createdAt: new Date().toISOString()
    }
    medicalTemplates.value.unshift(newTemplate)
    return newTemplate
  }

  const updateTemplate = async (id: string, updates: Partial<MedicalTemplate>) => {
    const index = medicalTemplates.value.findIndex(t => t.id === id)
    if (index > -1) {
      medicalTemplates.value[index] = { ...medicalTemplates.value[index], ...updates }
      return medicalTemplates.value[index]
    }
    throw new Error('模板不存在')
  }

  const deleteTemplate = async (id: string) => {
    const index = medicalTemplates.value.findIndex(t => t.id === id)
    if (index > -1) {
      medicalTemplates.value.splice(index, 1)
      return true
    }
    return false
  }

  // 应用模板到病历
  const applyTemplate = (templateId: string, recordId: string) => {
    const template = medicalTemplates.value.find(t => t.id === templateId)
    const record = medicalRecords.value.find(r => r.id === recordId)
    
    if (template && record) {
      record.chiefComplaint = template.content.chiefComplaint
      record.presentIllness = template.content.presentIllness
      record.physicalExamination = template.content.physicalExamination
      record.diagnosis.primary = [...template.content.diagnosis]
      record.treatment.advice = [...template.content.treatment]
      record.updatedAt = new Date().toISOString()
      
      return record
    }
    throw new Error('模板或病历不存在')
  }

  // 统计数据
  const getMedicalRecordStats = () => {
    const total = medicalRecords.value.length
    
    const byStatus = medicalRecords.value.reduce((acc, record) => {
      acc[record.status] = (acc[record.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byDepartment = medicalRecords.value.reduce((acc, record) => {
      acc[record.department] = (acc[record.department] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byVisitType = medicalRecords.value.reduce((acc, record) => {
      acc[record.visitType] = (acc[record.visitType] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const todayRecords = medicalRecords.value.filter(r => 
      r.visitDate === new Date().toISOString().split('T')[0]
    ).length

    const pendingSignatures = medicalRecords.value.filter(r => 
      r.status === '已完成' && r.signatures.length === 0
    ).length

    return {
      total,
      byStatus,
      byDepartment,
      byVisitType,
      todayRecords,
      pendingSignatures
    }
  }

  return {
    medicalRecords,
    medicalTemplates,
    currentRecord,
    searchQuery,
    filterStatus,
    filterDepartment,
    filterDateRange,
    loading,
    getMedicalRecords,
    getMedicalRecordById,
    getMedicalRecordsByPatient,
    getMedicalRecordsByDoctor,
    createMedicalRecord,
    updateMedicalRecord,
    deleteMedicalRecord,
    searchMedicalRecords,
    filterRecordsByStatus,
    filterRecordsByDepartment,
    filterRecordsByDateRange,
    signMedicalRecord,
    getPendingSignatureRecords,
    addAttachment,
    removeAttachment,
    getTemplates,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    applyTemplate,
    getMedicalRecordStats
  }
}, {
  persist: {
    key: 'medical-record-store',
    storage: localStorage,
    paths: ['medicalRecords', 'medicalTemplates']
  }
})